/*
 * @lc app=leetcode.cn id=106 lang=javascript
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function (inorder, postorder) {
  const buildTreeHelper = (postStart, postEnd, inStart, inEnd) => {
    if (postStart > postEnd) return null;
    const rootVal = postorder[postEnd];
    const root = new TreeNode(rootVal);
    const rootIndex = inorder.indexOf(rootVal);

    const rightTreeSize = inEnd - rootIndex;
    root.left = buildTreeHelper(
      postStart,
      postEnd - rightTreeSize - 1,
      inStart,
      rootIndex - 1
    );
    root.right = buildTreeHelper(
      postEnd - rightTreeSize,
      postEnd - 1,
      rootIndex + 1,
      inEnd
    );
    return root;
  };
  return buildTreeHelper(0, postorder.length - 1, 0, inorder.length - 1);
};
// @lc code=end
